package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.dao.ITravelCommentDAO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private ITravelCommentDAO travelCommentDAO;

    @Autowired
    private MongoTemplate template;


    @Override
    public String save(TravelComment comment) {
        if(comment.getId()==null){
            comment.setCreateTime(new Date());
        }
        travelCommentDAO.save(comment);
        return comment.getId();
    }

    @Override
    public List<TravelComment> list(){
        return travelCommentDAO.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
    }

    @Override
    public TravelComment get(String id) {
        Optional<TravelComment> op = travelCommentDAO.findById(id);
        return op.isPresent()?op.get():null;
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), sort);
        return travelCommentDAO.findAll(pageable);
    }

    @Override
    public Page<TravelComment> findByTravelId(TravelCommentQuery qo) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), sort);
        return travelCommentDAO.findByTravelId(qo.getTravelId(),  pageable);
    }


}
